package com.leenleda.ips.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.decard.NDKMethod.BasicOper;
import com.decard.NDKMethod.SSCardDriver;
import com.decard.entitys.IDCard;
import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.MyApplication;
import com.leenleda.ips.R;
import com.leenleda.ips.databinding.ActivityWebBinding;
import com.leenleda.ips.entity.IdCardMsg;
import com.leenleda.ips.entity.MarqueeEntity;
import com.leenleda.ips.net.AEvent;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.receiver.TimeReceiver;
import com.leenleda.ips.util.BitConverter;
import com.leenleda.ips.util.FileUtils;
import com.leenleda.ips.util.GsonUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.JavaScriptObject;
import com.leenleda.ips.util.NetUtils;
import com.leenleda.ips.util.TTSUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.UToast;
import com.leenleda.ips.util.Utils;
import com.leenleda.ips.widget.DialogAlert;
import com.leenleda.ips.widget.ScannerKeyEventHelper;
import com.sdt.Sdtapi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

public class WebActivity extends BaseActivity implements ScannerKeyEventHelper.OnScanSuccessListener {

    private static WebView webView;
    private FrameLayout mWebContainer;
    private ActivityWebBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_web);
        binding = (ActivityWebBinding) bindingView;
//        binding = DataBindingUtil.setContentView(this, R.layout.activity_web);

        LogUtils.e(tag, "======onCreate=======" );
        mWebContainer = findViewById(R.id.root);
        if (webView == null)
            webView = new WebView(MyApplication.getInstance().getApplicationContext());
        initWebView();
        mWebContainer.removeAllViews();

        ViewGroup parent = (ViewGroup) webView.getParent();
        if (parent != null)
            parent.removeView(webView);
        mWebContainer.addView(webView);

        binding.disconnect.setVisibility(Constant.NET_STATE ? View.GONE : View.VISIBLE);
        if (Constant.APP_TEST)
            return;
//        String ipStr = Utils.getStringValue(Utils.getString(Constant.SET_INPUT_IP));
//        if (!ipStr.isEmpty())
//            connectSer(ipStr);
//        PrintUtil.getInstance(this);
        binding.botL.setOnClickListener(v -> {
//            showPopVoice();
        });
        binding.botR.setOnClickListener(v -> {
//            try {
//                PcmToMp3.convertAudioFiles("/sdcard/speak_result.pcm", "/sdcard/speak_result.mp3");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        });
    }
    private int resL = 0, resR = 0;

    private DialogAlert dialogAlert;
    private JavaScriptObject javaScriptObject;
    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        WebSettings webSettings = webView.getSettings();//浏览器设置
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true);//浏览器启用JS
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //禁用缓存
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);  //禁用媒体播放硬件加速

        webSettings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);

        webView.setWebChromeClient(new WebChromeClient() { //启用Alert弹窗
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                if (dialogAlert != null)
                    dialogAlert.dismiss();
                dialogAlert = null;
                dialogAlert = new DialogAlert(WebActivity.this);
                dialogAlert.show(message);
                result.confirm();
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                showToast1("=1=shouldOverrideUrlLoading:" + url);
//                ILog.e(tag, "==sonReceived==houldOverrideUrlLoading====handler=======" + handler + "==url==" + url);
                if (url.contains("baiduboxapp") || url.contains("baiduboxlite") ){
                    return false;
                }
                loadUrl(url);
                return true;
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                showToast1("=2=onReceivedSslError:" + error);
//                ILog.e(tag, "==onReceivedSslError====handler==1=====" + handler + "==error==" + error);
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);//可能是加载插件失败
                showToast1("=3=onReceivedError:" + error);
//                ILog.e(tag, "==onReceivedSslError====handler===2====" + handler + "==error==" + error);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                reLoad = true;
                showToast1("=4=onReceivedError:" + failingUrl);
//                ILog.e(tag, "==onReceivedSslError====handler===3====" + handler + "==error==" + failingUrl);
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                showToast1("=5=onReceivedHttpError:" + errorResponse);
//                ILog.e(tag, "==onReceivedSslError====handler===4====" + handler + "==error==" + errorResponse);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                showToast1("=6=onPageFinished:" + url);
            }
        });

        javaScriptObject = new JavaScriptObject(this);
        webView.addJavascriptInterface(javaScriptObject, "IPSJavaObject");
    }

    private void showToast1(String str){
        LogUtils.e(tag, "==showToast1====" + str);
    }

    private boolean reLoad = true;
    @Override
    protected void onResume() {
        super.onResume();
//        ILog.e(tag, "======getMediaUrl=======" + BaseUtils.getBase());
        if (initState != 0)
            init();//社保卡初始化
        if (webView != null)
            webView.resumeTimers();
        String per = Utils.getStringValue(UShared.getString(Constant.DEVICE_PERMISSION_STATE));
        if (per.isEmpty())
            binding.tips.setVisibility(View.GONE);
        else {
            binding.tips.setText(per);
            binding.tips.setVisibility(View.VISIBLE);
        }
        loadUrl(1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null)
            webView.pauseTimers();
    }

    private void loadUrl(int position){
        if (webView == null)
            return;
//        mHandler.post(() ->{
//            binding.tipShow.setText("loadUrl: " + position);
//        });
        binding.start.setVisibility(Constant.APP_TEST ? View.GONE : dialogInput != null ? View.VISIBLE : View.GONE);
        LogUtils.e(tag, "loadUrl==test===" + Constant.APP_TEST + "==position==:" + position + "=dialogInput=" + dialogInput);

        StringBuilder load_end = new StringBuilder();
        load_end.append("position=");
        load_end.append(position);
        if (Constant.APP_TEST) {
            loadUrl(Constant.STATIC_URL_TEST);
            return;
        } else if (loadStaticWeb()) {
            misInput();
            UShared.putBooleanValue(Constant.LOAD_STATIC_URL, true);    //加载静态页面
            load_end.append(",loadStaticWeb");
            UShared.putString(Constant.WEB_LOAD_END, load_end.toString());
            binding.start.setVisibility(View.GONE);
            return;
        }
        UShared.putBooleanValue(Constant.LOAD_STATIC_URL, false);       //未加载静态页面
        if (dialogInput != null)
            return;
        LogUtils.e(tag, "loadUrl=====00000======" );
        if (!isNoAuthor()) {
            load_end.append(",isNoAuthor(暂无任务发布)");
            UShared.putString(Constant.WEB_LOAD_END, load_end.toString());
            binding.start.setVisibility(View.VISIBLE);
            loadUrl(Constant.STATIC_URL_BLANK);
            LogUtils.e(tag, "=====isNoAuthor()======" );
        }

        String url = getData();
        String type = getType();

        LogUtils.e(tag, "==type====" + type + ",url=" + url);
        if (url.trim().isEmpty()){
            LogUtils.e(tag, "==type22====" + type + ",url=" + url);
            loadUrl(Constant.STATIC_URL_BLANK);
        }else {
            switch (type){
                case Constant.PUBLISH_SOURCE:
                    Utils.startActivity(this, new Intent(this, ImageActivity.class));
                    finish();
                    return;
                case Constant.PUBLISH_WEB:
                    loadUrl(Utils.getStringValue(url));
                    break;
                case Constant.PUBLISH_LIVE:
                    Utils.startActivity(this, new Intent(this, LiveActivity.class));
                    finish();
                    return;
            }
        }

        load_end.append(",url=\"");
        load_end.append(url);
        load_end.append("\"");
        UShared.putString(Constant.WEB_LOAD_END, load_end.toString());
//        String filePath = FileUtils.getPath(Constant.CACHE_FOLDER);
//        Utils.deleteFolder(filePath);
    }

    private boolean loadStaticWeb(){
        String rootPath = "";
        try {
            rootPath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/LELDIPS/web";
            File file = new File(rootPath);
            LogUtils.e(tag, "loadUrl=====rootPath======" + rootPath);
            if (file.exists() && file.isDirectory()){
                File[] files = file.listFiles();
                LogUtils.e(tag, "loadUrl=====files.length======" + files.length);
                if (files.length > 0){
                    LogUtils.e(tag, "loadUrl=====files[0]======" + files[0]);
                    String loadUrl = files[0] + "/index.html";
                    File fil = new File(loadUrl);
                    LogUtils.e(tag, "loadUrl=====loadUrl======" + loadUrl);
                    LogUtils.e(tag, "loadUrl=====exists======" + fil.exists());
                    if (!fil.exists()){
                        FileUtils.deleteChild(file);
                        AEvent.notifyListener(AEvent.TO_TOAST, true, "静态网页地址index.html未找到");
                        return false;
                    }
                    loadUrl("file://" + loadUrl);
                    return true;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    //    private int showTime = 5, numberTime = 0, position = 0;
    @SuppressLint("JavascriptInterface")
    @Override
    public void conTrollShow(int state, String ... data) {
        switch (state){
            case 99://当加载失败时，重新加载
                boolean net = NetUtils.isNetworkAvailable(this);
//                ILog.e(tag, "======loadUrl====reLoad===" + reLoad + ",net=" + net + ",upUrl---1=" + upUrl );
                if(!reLoad)
                    return;
                if (!net)
                    return;
                if (Utils.getStringValue(upUrl).isEmpty())
                    return;
                LogUtils.e(tag, "======loadUrl====reLoad===" + reLoad + ",upUrl---2=" + upUrl );
                loadUrl("");
                break;
            case Constant.PUSH_ROLL_MSG://显示滚动消息
                String msgData = data[0];
                MarqueeEntity bean = GsonUtils.getInstance().fromJson(msgData, MarqueeEntity.class);
                LogUtils.e(tag, "==bundle===bean======" + bean);
                if (bean.getRollTime() < 1){
                    missRollMsg(true);
                    return;
                }
                showRollMsg(bean);
                break;
            case Constant.MISS_ROLL_MSG:
                LogUtils.e(tag, "=====MISS_ROLL_MSG======" );
                missRollMsg(false);
                break;
            case Constant.DEVICE_PERMISSION_FALSE://提示到期
                LogUtils.e(tag, "-EVICE----false--" + data[0]);
                binding.tips.setVisibility(View.VISIBLE);
                binding.tips.setText(data[0]);
                break;
            case Constant.DEVICE_PERMISSION_TRUE:
//                ILog.e(tag, "-EVICE----true--" + data[0]);
                binding.tips.setVisibility(View.GONE);
                break;
            case Constant.INTERNET_CHANGE:
                LogUtils.e("SKDVSDNSDLV", "=====NET_STATE==2====" + Constant.NET_STATE  );
                binding.disconnect.setVisibility(Constant.NET_STATE ? View.GONE : View.VISIBLE);
                break;
            case Constant.SET_MEDIA_DATA:
                LogUtils.e(tag, "====web=======" + data[0]);

                if (isNoAuthor() || data[0].equalsIgnoreCase(Constant.PUBLISH_WEB)) {
                    loadUrl(2);
                    return;
                }
                String url = getData();
                if (url.trim().isEmpty()){
                    loadUrl(3);
                } else {

                    String type = getType();
                    LogUtils.e(tag, "==type====" + type + ",url=" + url);
                    switch (type){
                        case Constant.PUBLISH_SOURCE:
                            Utils.startActivity(this, new Intent(this, ImageActivity.class));
                            finish();
                            return;
                        case Constant.PUBLISH_WEB:
                            loadUrl(31);
                            break;
                        case Constant.PUBLISH_LIVE:
                            Utils.startActivity(this, new Intent(this, LiveActivity.class));
                            finish();
                            return;
                    }
                }
                break;
            case Constant.REFRESH_WEB:
                webViewGC(1);
                break;
            case Constant.SHOW_TOAST://吐司
                AEvent.notifyListener(AEvent.TO_TOAST, true, data[0]);
                break;
            case Constant.REFRESH_JS://加载Js
                LogUtils.e(tag, "==REFRESH_JS==" + data );
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                    webView.evaluateJavascript(data[0], null);
                else
                    webView.addJavascriptInterface(data[0], "jsObj");
                break;
        }
    }


    private String upUrl = "";
    private void loadUrl(String url){
        reLoad = false;
        LogUtils.e(tag, "======loadUrl===1====" + url + ",upUrl11=" + upUrl );
        if (url.isEmpty()){
            webView.loadUrl(Constant.STATIC_URL_BLANK);
            return;
        }
        LogUtils.e(tag, "======loadUrl===2====" + url);
        webView.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
        LogUtils.e(tag, "======onDestroy=======" );

        if (handler != null)
            handler.removeCallbacksAndMessages(null);
        mWebContainer.removeAllViews();
        if(webView != null) {
            Utils.clearAllCache(this);
            webView.clearHistory();
            webView.clearCache(true);
            loadUrl("about:blank"); // clearView() should be changed to loadUrl("about:blank"), since clearView() is deprecated now
            webView.freeMemory();
            webView.pauseTimers();
            webView.destroy();
            webView = null; // Note that mWebView.destroy() and mWebView = null do the exact same thing
        }
        super.onDestroy();
    }

    public void webViewGC(int position){
        LogUtils.e(tag, "===webViewGC=="  + position);
        if (webView == null)
            return;
        mHandler.post(() -> {
            UToast.showToast("重新加载" + TimeReceiver.connectNum);
            Utils.clearAllCache(WebActivity.this);
            webView.clearHistory();
            webView.clearCache(true);
            webView.freeMemory();
            webView.reload();
        });
    }


    private MediaPlayer mediaPlayer = null;
    private AssetFileDescriptor file = null;
    public void playBee(int source) {
        if (mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            file = getResources().openRawResourceFd(source);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                mediaPlayer.setVolume(0, 1);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if ( mediaPlayer != null) {
            mediaPlayer.start();
        }
        mediaPlayer.setOnCompletionListener(mp -> {
            mp.pause();
            mp.seekTo(0);
        });
    }


//*************************生份证读取****************************************************


    public void readResult(String type, String name, String sex, String nation, String number, String address){
        if (overTime != 0) {//持续读卡
            autoTime = 0;//结束循环读卡
            LogUtils.e(tag, "====booOver===overTime==Over=22====" + autoTime );
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", type);
            jsonObject.put("name", name.trim());
            jsonObject.put("sex", sex);
            jsonObject.put("nation", nation);
            jsonObject.put("number", number);
            jsonObject.put("address", address.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.e(tag, "==jsonObject----------==" + jsonObject);
        String js = String.format("javascript:OnCardRead('%s');", jsonObject.toString());
        packLoadJs(js);
    }

    public void readSuccess(String name, String number, String type){
        switch (type){
            case "1":
            case "2":
            case "3":
                if (overTime != 0) {//持续读卡
                    autoTime = 0;//结束循环读卡
                }
                break;
            default:
                break;
        }
        LogUtils.e(tag, "====booOver===overTime==Over=20====" + autoTime );
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", name);
            jsonObject.put("number", number);
            jsonObject.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String js = String.format("javascript:OnCardRead('%s');", jsonObject.toString());
        LogUtils.e(tag, "=====jsonObject============" + jsonObject);
        packLoadJs(js);
    }

    /**
     * 统一发送加载 JS
     */
    private void packLoadJs(String js){
        Intent intent = new Intent(Constant.TIMER_LOOP_ACTION);
        Bundle bundle = new Bundle();
        bundle.putInt("state", Constant.REFRESH_JS);
        bundle.putString("data", js);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }


    /**
     * 扫码处理对象
     */
    private ScannerKeyEventHelper mScannerKeyEventHelper;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_UNKNOWN)
            return super.dispatchKeyEvent(event);
        LogUtils.e(tag, "=======getKeyCode========" + event.getKeyCode());
        if (mScannerKeyEventHelper == null)
            mScannerKeyEventHelper = new ScannerKeyEventHelper(this);//扫码
        mScannerKeyEventHelper.analysisKeyEvent(event);
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void OnScanSuccess(String barcode) {
        LogUtils.e(tag, "=======OnScanSuccess===1=====" + barcode);
        LogUtils.e(tag, "=======OnScanSuccess===2=====" + isFirst());
        String js = String.format("javascript:OnScan('%s');", barcode);
        packLoadJs(js);
    }
    private String tag = "WebActivity";


//************************************************************  读卡

    public static long overTime = 0l;
    public void oneAutoCard(int time, int state, int showTime){// 每相隔showTime秒后，读取一次。持续时间time秒结束
        overTime = System.currentTimeMillis() + time * 1000;
        autoCard(state, showTime);
    }

    public void autoCard(int state, int showTime){
        this.cardState = state;
        this.autoTime = showTime;
        if (handler == null){
            getHandler();
            cardLoop();
        }
        LogUtils.e(tag, "======autoTime===getHandler====autoTime=" + autoTime);
    }

    private Handler handler;
    private int autoTime = 0;
    private int cardState = 0;
    private Handler getHandler(){
        if (handler == null)
            handler = new Handler();
        LogUtils.e(tag, "======autoTime===getHandler====handler=" + handler);
        return handler;
    }

    /**
     * 自动读卡
     */
    public void cardLoop(){
        booOver();
        if (autoTime < 1){
            handler = null;
            autoTime = 0;
            return;
        }
        LogUtils.e(tag, "======autoTime===startLoop*********************====" + autoTime);
        handler.postDelayed(() ->{
            booOver();
            if (autoTime < 1){
                handler = null;
                autoTime = 0;
                return;
            }
            cardLoop();
            switch (cardState){
                case 1:
                    readM1Card();
                    break;
                case 2:
                    readSecure();
                    break;
                case 3:
                    readIDCard();
                    break;
                case 5:
                    readCardSDT();
                    break;
            }
        } , autoTime * 1000);
    }

    private void booOver(){
        if (overTime != 0){
            long curTime = System.currentTimeMillis();
            LogUtils.e(tag, "====booOver===overTime=----=" + overTime + ", autoTime=" + autoTime);
            if (curTime > overTime) {
                autoTime = 0;// 到达设定时限，结束循环读卡
                LogUtils.e(tag, "====booOver===overTime==Over=1====" + autoTime );
                readSuccess("持续读卡", "读卡失败:", "-1");
            } else {

            }
        }
    }

    private int deka_USB = 0;
    public void openUSB(){
        new Handler().post(() -> {
//            BasicOper.dc_setLanguageEnv(1);
            BasicOper.dc_AUSB_ReqPermission(this);//向系统申请使用USB权限,此过程为异步,建议放在程序启动时调用。
            int devHandle = BasicOper.dc_open("AUSB",this,"",0); //打开端口，usb模式，打开之前必须确保已经获取到USB权限，返回值为设备句柄号。
            deka_USB = devHandle;
            LogUtils.e("open","dc_open success deka_USB = "+deka_USB);
            readState = false;
        });
    }

    /**
     * 身份证
     */
    public void readIDCard(){
        if (deka_USB < 1){
            openUSB();
            mHandler.post(() -> {
                UToast.showToast("openUSB");
            });
            return;
        }
        IDCard idCard = BasicOper.dc_SamAReadCardInfo(1);
        if(idCard!=null) {
            readResult("1", idCard.getName(), idCard.getSex(), idCard.getNation(), idCard.getId(), idCard.getAddress());
            readState = false;
            return;
        } else {
            readSuccess("身份证",  "读卡失败,", "-1");
        }
        if (autoTime < 1) {
            TTSUtils.getInstance().speak(this, "请先放置好身份证", -1);
        }
        readState = false;
    }

    /**
     * 就诊卡
     */
    public void readM1Card(){// 寻卡,防冲撞,选卡三合一
        if (deka_USB < 1){
            openUSB();
            mHandler.post(() -> {
                UToast.showToast("openUSB");
            });
            return;
        }
        String result = null;
        String[] resultArr = null;
        result = BasicOper.dc_card_n_hex(1);
        resultArr = result.split("\\|",-1);
        if(resultArr[0].equals("0000")){
            LogUtils.e(tag,"====m1Find========success 卡片序列号："+resultArr[1]);
            String res = resultArr[1];
            byte[] aa = BitConverter.hexStringToBytes(res);
            LogUtils.e(tag, "=========aa=====" + aa);
            int dd = BitConverter.ToInt32(aa, 0);
            String data = dd + "";
            if (data.length() < 10)
                data = "0" + data;
            LogUtils.e(tag, "=========dd=====" + dd);
            readSuccess("就诊卡", data, "2");
            readState = false;
            return;
        }else{
            readSuccess("就诊卡",  "读卡失败,", "-1");
            LogUtils.e(tag,"====m1Find========error code = "+resultArr[0] +" error msg = "+resultArr[1] );
            readState = false;
            return;
        }

//        result = BasicOper.dc_authentication_pass(0,0,"7975616E7475");
//        resultArr = result.split("\\|",-1);
//        if(resultArr[0].equals("0000")){
//            LogUtils.e(tag,"====m1Pwd========success");
//        }else{
//            LogUtils.e(tag,"====m1Pwd========error code = "+resultArr[0] +" error msg = "+resultArr[1] );
//            readState = false;
//            return;
//        }
//
//        result = BasicOper.dc_read_hex(0);
//        resultArr = result.split("\\|",-1);
//        if(resultArr[0].equals("0000")){
//            String data = resultArr[1];
//            LogUtils.e(tag,"===m1Read=========success data : "+data);
//            readSuccess("就诊卡", data, "2");
//            readState = false;
//            return;
//        } else {
//            readSuccess("就诊卡",  "读卡失败,", "-1");
//        }
//        readState = false;
//        if (autoTime < 1) {
//            TTSUtils.getInstance().speak(this, "请先放置好就诊卡", -1);
//        }
    }

    /**
     * 社保卡
     */
    public void readSecure(){
        new Thread(() -> {
            byte[] info = new byte[1024];
            String data = "";
            SSCardDriver.iReadCardBas(1, info);// 1,接 2,非接       3,自动接优先  4,自动非接优先
            String err = "";
            try {//410700|410703195810153516|G62204160|410700D1560000
                data = new String(info,"gbk").trim();
                LogUtils.e(tag,"===readSecure=========success data : "+data);
//                if (true){
//                    readSuccess("社保卡1", data, "3");
//                    return;
//                }
                String[] bb = data.replace("|", ",").split(",");//  data = "410700|410703195810153516|G62204160|410700D1560000";
                if (bb != null){
                    readState = false;
                    String number = bb[1];
                    String name = bb[4];
                    readSuccess("社保卡", number, "3");
                    return;
                }
            } catch (Exception e) {
                LogUtils.e(tag,"===readSecure=========success e : " + e);
                init();
                err = e + "";
            }
            readState = false;
            readSuccess("社保卡", "读卡失败:" + err, "-1");
            if (autoTime < 1) {
                TTSUtils.getInstance().speak(this, "请先放置好社保卡", -1);
            }
        }).start();
    }

    public static boolean readState = false;
    public static long readTime = 0l;
    private int initState = -1;
    private void init(){
        initState = BasicOper.setInitParameter(2, null, 0);
        LogUtils.e(tag,"===readSecure=========init : " + initState);
        BasicOper.CreateAndroidContext(getApplicationContext());
    }
//         NetConstants.BASE_URL="http://10.85.200.99/";  //设置密服地址  新乡
//         NetConstants.ACCOUNT="admin|admin";//设置登录用户名密码





//================================

    Sdtapi sdta;
    public void readCardSDT(){
        if (sdta == null){
            try {
                sdta= new Sdtapi(this);
            } catch (Exception e1) {//捕获异常，
                AEvent.notifyListener(AEvent.TO_TOAST, true, "USB设备异常或无连接");
                return;
            }
        }
        int ret;
        String show = "";
        sdta.SDT_StartFindIDCard();//寻找身份证
        sdta.SDT_SelectIDCard();//选取身份证
        IdCardMsg msg = new IdCardMsg();//身份证信息对象，存储身份证上的文字信息

        ret =ReadBaseMsgToStr(msg);
        if(ret==0x90) {
            show =   "姓名:"+msg.name+'\n'
                    +"性别:"+msg.sex+'\n'
                    +"民族:"+msg.nation_str+"族"+'\n'
                    +"出生日期:"+msg.birth_year+"-"+msg.birth_month+"-"+msg.birth_day+'\n'
                    +"住址:"+msg.address+'\n'
                    +"身份证号码:"+msg.id_num+'\n'
                    +"签发机关:"+msg.sign_office+'\n'
                    +"有效期起始日期:"+msg.useful_s_date_year+"-"+msg.useful_s_date_month+"-"+msg.useful_s_date_day+'\n'
                    +"有效期截止日期:"+msg.useful_e_date_year+"-"+msg.useful_e_date_month+"-"+msg.useful_e_date_day+'\n';
            readResult("1", msg.name, msg.sex, msg.nation_str, msg.id_num, msg.address);
        } else{
            show ="读基本信息失败:"+String.format("0x%02x", ret);
            if (autoTime < 1)
                TTSUtils.getInstance().speak(this, "请先放置好身份证", -1);
        }
        LogUtils.e(tag, "=====show========" + show);
    }
//    public void readResult(String type, String name, String sex, String nation, String number, String address){

    //读取身份证中的文字信息（可阅读格式的）
    public int ReadBaseMsgToStr(IdCardMsg msg) {
        int ret;
        int []puiCHMsgLen=new int[1];
        int []puiPHMsgLen=new int[1];

        byte [] pucCHMsg = new byte[256];
        byte [] pucPHMsg = new byte[1024];

        ret =sdta.SDT_ReadBaseMsg( pucCHMsg, puiCHMsgLen, pucPHMsg, puiPHMsgLen);//sdtapi中标准接口，输出字节格式的信息。
        if(ret==0x90) {
            try {
                char [] pucCHMsgStr = new char[128];
                DecodeByte(pucCHMsg,pucCHMsgStr);//将读取的身份证中的信息字节，解码成可阅读的文字
                PareseItem(pucCHMsgStr,msg); //将信息解析到msg中
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ret;
    }
    //字节解码函数
    void DecodeByte(byte[] msg,char []msg_str) throws Exception {
        byte[] newmsg = new byte[msg.length+2];

        newmsg[0]=(byte) 0xff;
        newmsg[1] =(byte) 0xfe;

        for(int i=0;i<msg.length;i++)
            newmsg[i+2]= msg[i];

        String s=new String(newmsg,"UTF-16");
        for(int i=0;i<s.toCharArray().length;i++)
            msg_str[i]=s.toCharArray()[i];
    }
    //分段信息提取
    void  PareseItem(char []pucCHMsgStr, IdCardMsg msg) {
        msg.name = String.copyValueOf(pucCHMsgStr, 0, 15);
        String sex_code = String.copyValueOf(pucCHMsgStr, 15, 1);

        if(sex_code.equals("1")) msg.sex="男";
        else if(sex_code.equals("2"))msg.sex="女";
        else if(sex_code.equals("0"))msg.sex="未知";
        else if (sex_code.equals("9"))msg.sex="未说明";

        String nation_code = String.copyValueOf(pucCHMsgStr, 16, 2);
        msg.nation_str = nation[Integer.valueOf(nation_code)-1];
        msg.birth_year = String.copyValueOf(pucCHMsgStr, 18, 4);
        msg.birth_month = String.copyValueOf(pucCHMsgStr, 22, 2);
        msg.birth_day = String.copyValueOf(pucCHMsgStr, 24, 2);
        msg.address = String.copyValueOf(pucCHMsgStr, 26, 35);
        msg.id_num = String.copyValueOf(pucCHMsgStr, 61, 18);
        msg.sign_office = String.copyValueOf(pucCHMsgStr, 79, 15);
        msg.useful_s_date_year = String.copyValueOf(pucCHMsgStr, 94, 4);
        msg.useful_s_date_month = String.copyValueOf(pucCHMsgStr, 98, 2);
        msg.useful_s_date_day = String.copyValueOf(pucCHMsgStr, 100, 2);
        msg.useful_e_date_year = String.copyValueOf(pucCHMsgStr, 102, 4);
        msg.useful_e_date_month = String.copyValueOf(pucCHMsgStr, 106, 2);
        msg.useful_e_date_day = String.copyValueOf(pucCHMsgStr, 108, 2);
    }
    /*民族列表*/
    String [] nation ={"汉","蒙古","回","藏","维吾尔","苗","彝","壮","布依","朝鲜",
            "满","侗","瑶","白","土家","哈尼","哈萨克","傣","黎","傈僳",
            "佤","畲","高山","拉祜","水","东乡","纳西","景颇","克尔克孜","土",
            "达斡尔","仫佬","羌","布朗","撒拉","毛南","仡佬","锡伯","阿昌","普米",
            "塔吉克","怒","乌兹别克","俄罗斯","鄂温克","德昂","保安","裕固","京","塔塔尔",
            "独龙","鄂伦春","赫哲","门巴","珞巴","基诺"};

}